import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, Select, Space, Tag, Modal, message, Descriptions, Popconfirm, InputNumber, Row, Col, Divider } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';
import FacilityEditor from './FacilityEditor';
import ImageUploader from './ImageUploader';
import TimeBasedPricingEditor from './TimeBasedPricingEditor';
import VenueTimeline from './VenueTimeline';

const { Option } = Select;
const { TextArea } = Input;

// 获取场地列表
const fetchVenues = async (params) => {
    return request('/api/v1/venue', {
        method: 'GET',
        params,
    });
};

// 获取场地列表（时间线视图）
const fetchVenuesForTimeline = async (params) => {
    return request('/api/v1/venue/timeline_list', {
        method: 'GET',
        params,
    });
};

// 获取场地详情
const fetchVenueDetail = async (id) => {
    return request(`/api/v1/venue/${id}`, {
        method: 'GET',
    });
};

// 创建场地
const createVenue = async (data) => {
    return request('/api/v1/venue', {
        method: 'POST',
        data,
    });
};

// 更新场地
const updateVenue = async (id, data) => {
    return request(`/api/v1/venue/${id}`, {
        method: 'PUT',
        data,
    });
};

// 删除场地
const deleteVenue = async (id) => {
    return request(`/api/v1/venue/${id}`, {
        method: 'DELETE',
    });
};

// 获取门店列表
const fetchStores = async () => {
    return request('/api/v1/store', {
        method: 'GET',
        params: { pageSize: 100 },
    });
};

const StoreVenue = () => {
    const [venues, setVenues] = useState([]);
    const [stores, setStores] = useState([]);
    const [loading, setLoading] = useState(false);
    const [form] = Form.useForm();
    const [venueForm] = Form.useForm();
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    const [searchParams, setSearchParams] = useState({});
    const [detailVisible, setDetailVisible] = useState(false);
    const [formVisible, setFormVisible] = useState(false);
    const [currentVenue, setCurrentVenue] = useState(null);
    const [formTitle, setFormTitle] = useState('创建场地');
    const [viewMode, setViewMode] = useState('table'); // 'table' or 'timeline'
    const [venue_types, setvenue_types] = useState([]);

    // 获取场地列表
    const fetchVenueList = async () => {
        try {
            setLoading(true);
            console.log("fetchVenueList:",viewMode)
            const fetcher = viewMode === 'table' ? fetchVenues : fetchVenuesForTimeline;
            const pageSize = viewMode ==='table' ? pagination.pageSize:30;
            const res = await fetcher({
                page: pagination.current,
                pageSize: pageSize,
                ...searchParams,
            });
            if (res.success) {
                setVenues(res.data.list || []);
                setPagination({
                    ...pagination,
                    total: res.data.total,
                });
            } else {
                message.error(res.message || '获取场地列表失败');
            }
        } catch (error) {
            console.error('获取场地列表出错:', error);
            message.error('获取场地列表失败');
        } finally {
            setLoading(false);
        }
    };
    
    // 获取场地类型列表
    const fetchvenue_types = async () => {
        try {
            const res = await request('/api/v1/venue/type', {
                method: 'GET',
            });
            if (res.success) {
                const types = res.data.map(item => ({
                    label: item.name,
                    value: item.name,
                    id: item.id
                }));
                setvenue_types(types);
            } else {
                message.error(res.message || '获取场地类型失败');
            }
        } catch (error) {
            console.error('获取场地类型出错:', error);
            // 设置默认场地类型，以防API调用失败
            setvenue_types([]);
        }
    };

    // 获取门店列表
    const fetchStoreList = async () => {
        try {
            const res = await fetchStores();
            if (res.success) {
                setStores(res.data.list || []);
            } else {
                message.error(res.message || '获取门店列表失败');
            }
        } catch (error) {
            console.error('获取门店列表出错:', error);
            message.error('获取门店列表失败');
        }
    };

    useEffect(() => {
        fetchVenueList();
        fetchStoreList();
        fetchvenue_types();
    }, [pagination.current, pagination.pageSize, searchParams, viewMode]);

    // 查看场地详情
    const handleViewDetail = async (record) => {
        try {
            setLoading(true);
            const res = await fetchVenueDetail(record.id);
            if (res.success) {
                setCurrentVenue(res.data);
                setDetailVisible(true);
            } else {
                message.error(res.message || '获取场地详情失败');
            }
        } catch (error) {
            console.error('获取场地详情出错:', error);
            message.error('获取场地详情失败');
        } finally {
            setLoading(false);
        }
    };

    // 处理添加场地
    const handleAdd = () => {
        setFormTitle('创建场地');
        setCurrentVenue(null);
        venueForm.resetFields();
        venueForm.setFieldsValue({
            status: 1,
            facilities:[],
            images: [],
        });
        setFormVisible(true);
    };

    // 处理编辑场地
    const handleEdit = (record) => {
        setFormTitle('编辑场地');
        setCurrentVenue(record);
        venueForm.resetFields();
        venueForm.setFieldsValue({
            name: record.name,
            store_id: record.store_id,
            capacity: record.capacity,
            area: record.area,
            hour_price: record.hour_price,
            time_based_pricing: record.time_based_pricing,
            day_price: record.day_price,
            description: record.description,
            facilities: record.facilities,
            images: record.images,
            venue_type: record.venue_type,
            status: record.status,
            sort_order: record.sort_order,
            opening_hours: record.opening_hours,
        });
        setFormVisible(true);
    };

    // 处理删除场地
    const handleDelete = async (id) => {
        try {
            setLoading(true);
            const res = await deleteVenue(id);
            if (res.success) {
                message.success('删除场地成功');
                fetchVenueList();
            } else {
                message.error(res.message || '删除场地失败');
            }
        } catch (error) {
            console.error('删除场地出错:', error);
            message.error('删除场地失败');
        } finally {
            setLoading(false);
        }
    };

    // 提交表单
    const handleFormSubmit = async () => {
        try {
            const values = await venueForm.validateFields();
            setLoading(true);

            let res;
            if (currentVenue) {
                // 更新
                res = await updateVenue(currentVenue.id, values);
            } else {
                // 创建
                res = await createVenue(values);
            }

            if (res.success) {
                message.success(`${currentVenue ? '更新' : '创建'}场地成功`);
                setFormVisible(false);
                fetchVenueList();
            } else {
                message.error(res.message || `${currentVenue ? '更新' : '创建'}场地失败`);
            }
        } catch (error) {
            console.error(`${currentVenue ? '更新' : '创建'}场地出错:`, error);
            message.error(`${currentVenue ? '更新' : '创建'}场地失败`);
        } finally {
            setLoading(false);
        }
    };

    // 处理搜索
    const handleSearch = (values) => {
        const params = {};
        if (values.name) {
            params.name = values.name;
        }
        if (values.store_id) {
            params.store_id = values.store_id;
        }
        if (values.status !== undefined) {
            params.status = values.status;
        }
        if (values.venue_type) {
            params.venue_type = values.venue_type;
        }

        setSearchParams(params);
        setPagination({
            ...pagination,
            current: 1,
        });
    };

    // 处理重置
    const handleReset = () => {
        form.resetFields();
        setSearchParams({});
        setPagination({
            ...pagination,
            current: 1,
        });
    };

    // 表格列定义
    const columns = [
        {
            title: '场地名称',
            dataIndex: 'name',
            key: 'name',
            width: 150,
        },
        {
            title: '所属门店',
            dataIndex: 'store_id',
            key: 'store_id',
            width: 150,
            render: (text) => {
                const store = stores.find(s => s.id === text);
                return store ? store.name : text;
            },
        },
        {
            title: '场地类型',
            dataIndex: 'venue_type',
            key: 'venue_type',
            width: 120,
            render: (text) => {
                const type = venue_types.find(t => t.value === text);
                return type ? type.label : text;
            },
        },
        {
            title: '容纳人数',
            dataIndex: 'capacity',
            key: 'capacity',
            width: 100,
        },
        {
            title: '小时价格',
            dataIndex: 'hour_price',
            key: 'hour_price',
            width: 120,
            render: (text) => `¥${(text).toFixed(2)}`,
        },
        {
            title: '全天价格',
            dataIndex: 'day_price',
            key: 'day_price',
            width: 120,
            render: (text) => `¥${(text).toFixed(2)}`,
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: 100,
            render: (status) => {
                let color = 'default';
                let text = '未知';
                
                switch(status) {
                    case 1: // 空闲中
                        color = 'green';
                        text = '空闲中';
                        break;
                    case 2: // 使用中
                        color = 'blue';
                        text = '使用中';
                        break;
                    case 3: // 保洁中
                        color = 'orange';
                        text = '保洁中';
                        break;
                    case 4: // 待保洁
                        color = 'gold';
                        text = '待保洁';
                        break;
                    case 5: // 维护中
                        color = 'red';
                        text = '维护中';
                        break;
                    default:
                        color = 'default';
                        text = '未知';
                }
                
                return <Tag color={color}>{text}</Tag>;
            },
        },
        {
            title: '创建时间',
            dataIndex: 'created_at',
            key: 'created_at',
            width: 180,
            render: (text) => moment(text*1000).format('YYYY-MM-DD HH:mm:ss'),
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button
                        type="link"
                        icon={<EyeOutlined />}
                        onClick={() => handleViewDetail(record)}
                    >
                        详情
                    </Button>
                    <Button
                        type="link"
                        icon={<EditOutlined />}
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Popconfirm
                        title="确定要删除此场地吗？"
                        onConfirm={() => handleDelete(record.id)}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button
                            type="link"
                            icon={<DeleteOutlined />}
                            danger
                        >
                            删除
                        </Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ];

    // 处理表格变化
    const handleTableChange = (pagination, filters, sorter) => {
        setPagination(pagination);
    };

    return (
        <PageContainer>
            <Card style={{ marginBottom: 24 }}>
                <Form
                    form={form}
                    layout="inline"
                    onFinish={handleSearch}
                    style={{ marginBottom: 24 }}
                >
                    <Form.Item name="name" label="场地名称">
                        <Input placeholder="请输入场地名称" style={{ width: 200 }} />
                    </Form.Item>
                    <Form.Item name="store_id" label="所属门店">
                        <Select placeholder="请选择门店" style={{ width: 200 }} allowClear>
                            {stores.map(store => (
                                <Option key={store.id} value={store.id}>{store.name}</Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item name="venue_type" label="场地类型">
                        <Select placeholder="请选择场地类型" style={{ width: 200 }} allowClear>
                            {venue_types.map(type => (
                                <Option key={type.value} value={type.value}>{type.label}</Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item name="status" label="状态">
                        <Select placeholder="请选择状态" style={{ width: 200 }} allowClear>
                            <Option value={1}>空闲中</Option>
                            <Option value={2}>使用中</Option>
                            <Option value={3}>保洁中</Option>
                            <Option value={4}>待保洁</Option>
                            <Option value={5}>维护中</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item>
                        <Space>
                            <Button type="primary" htmlType="submit">
                                查询
                            </Button>
                            <Button onClick={handleReset}>重置</Button>
                        </Space>
                    </Form.Item>
                </Form>

                <div style={{ marginBottom: 16 }}>
                                        <Button onClick={() => {
                                            setViewMode(viewMode === 'table' ? 'timeline' : 'table')
                                        }}>
                        {viewMode === 'table' ? '切换到时间线视图' : '切换到表格视图'}
                    </Button>
                    <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                        创建场地
                    </Button>
                </div>

                                {viewMode === 'table' ? (
                    <Table
                        columns={columns}
                        dataSource={venues}
                        rowKey="id"
                        loading={loading}
                        pagination={pagination}
                        onChange={handleTableChange}
                        scroll={{ x: 1200 }}
                    />
                ) : (
                    <VenueTimeline venues={venues} loading={loading} />
                )}
            </Card>

            {/* 场地详情弹窗 */}
            <Modal
                title="场地详情"
                visible={detailVisible}
                onCancel={() => setDetailVisible(false)}
                footer={null}
                width={700}
            >
                {currentVenue && (
                    <Descriptions bordered column={2}>
                        <Descriptions.Item label="场地名称" span={2}>{currentVenue.name}</Descriptions.Item>
                        <Descriptions.Item label="所属门店">{stores.find(s => s.id === currentVenue.store_id)?.name || currentVenue.store_id}</Descriptions.Item>
                        <Descriptions.Item label="场地类型">
                            {venue_types.find(t => t.value === currentVenue.venue_type)?.label || currentVenue.venue_type}
                        </Descriptions.Item>
                        <Descriptions.Item label="状态">
                            {(() => {
                                let color = 'default';
                                let text = '未知';
                                
                                switch(currentVenue.status) {
                                    case 1: // 空闲中
                                        color = 'green';
                                        text = '空闲中';
                                        break;
                                    case 2: // 使用中
                                        color = 'blue';
                                        text = '使用中';
                                        break;
                                    case 3: // 保洁中
                                        color = 'orange';
                                        text = '保洁中';
                                        break;
                                    case 4: // 待保洁
                                        color = 'gold';
                                        text = '待保洁';
                                        break;
                                    case 5: // 维护中
                                        color = 'red';
                                        text = '维护中';
                                        break;
                                    default:
                                        color = 'default';
                                        text = '未知';
                                }
                                
                                return <Tag color={color}>{text}</Tag>;
                            })()}
                        </Descriptions.Item>
                        <Descriptions.Item label="容纳人数">{currentVenue.capacity}人</Descriptions.Item>
                        <Descriptions.Item label="面积">{currentVenue.area}平方米</Descriptions.Item>
                        <Descriptions.Item label="默认小时价格">{`¥${(currentVenue.hour_price).toFixed(2)}`}</Descriptions.Item>
                        <Descriptions.Item label="分时段定价" span={2}>
                            {currentVenue.time_based_pricing ? (
                                <div>
                                    {(() => {
                                        try {
                                            const pricingArray = JSON.parse(currentVenue.time_based_pricing);
                                            return pricingArray.map((p, index) => (
                                                <Tag key={index}>{`${p.start_time}-${p.end_time}: ¥${p.price}`}</Tag>
                                            ));
                                        } catch (e) {
                                            return currentVenue.time_based_pricing;
                                        }
                                    })()}
                                </div>
                            ) : '-'}
                        </Descriptions.Item>
                        <Descriptions.Item label="全天价格">{`¥${(currentVenue.day_price).toFixed(2)}`}</Descriptions.Item>
                        <Descriptions.Item label="创建时间" span={2}>{moment(currentVenue.created_at*1000).format('YYYY-MM-DD HH:mm:ss')}</Descriptions.Item>
                        <Descriptions.Item label="特殊提示" span={2}>{currentVenue.special_notice}</Descriptions.Item>
                        <Descriptions.Item label="描述" span={2}>{currentVenue.description}</Descriptions.Item>
                        <Descriptions.Item label="设施" span={2}>
                            {currentVenue.facilities ? (
                                <div>
                                    {(() => {
                                        try {
                                            const facilitiesArray = JSON.parse(currentVenue.facilities);
                                            return facilitiesArray.map(facility => (
                                                <Tag key={facility} style={{ margin: '0 4px 4px 0' }}>{facility}</Tag>
                                            ));
                                        } catch (e) {
                                            // 如果解析失败，尝试按逗号分隔
                                            return currentVenue.facilities.split(',').map(item => item.trim()).filter(Boolean).map(facility => (
                                                <Tag key={facility} style={{ margin: '0 4px 4px 0' }}>{facility}</Tag>
                                            ));
                                        }
                                    })()} 
                                </div>
                            ) : '-'}
                        </Descriptions.Item>
                        <Descriptions.Item label="场地图片" span={2}>
                            {currentVenue.images ? (
                                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
                                    {(() => {
                                        try {
                                            const imagesArray = JSON.parse(currentVenue.images);
                                            return imagesArray.map((image, index) => (
                                                <img 
                                                    key={index} 
                                                    src={image} 
                                                    alt={`场地图片${index+1}`} 
                                                    style={{ width: '120px', height: '120px', objectFit: 'cover' }} 
                                                />
                                            ));
                                        } catch (e) {
                                            // 如果解析失败，可能是单个URL
                                            return (
                                                <img 
                                                    src={currentVenue.images} 
                                                    alt="场地图片" 
                                                    style={{ width: '120px', height: '120px', objectFit: 'cover' }} 
                                                />
                                            );
                                        }
                                    })()}
                                </div>
                            ) : '-'}
                        </Descriptions.Item>
                    </Descriptions>
                )}
            </Modal>

            {/* 新增/编辑场地弹窗 */}
            <Modal
                title={formTitle}
                visible={formVisible}
                onCancel={() => setFormVisible(false)}
                footer={null}
                width={700}
                destroyOnClose
            >
                <Form
                    form={venueForm}
                    name="venueForm"
                    onFinish={handleFormSubmit}
                    autoComplete="off"
                    layout="vertical"
                    initialValues={currentVenue}
                    preserve={false} // 重置表单时，重置到初始值，而不是清空
                >
                    <Form.Item
                        label="场地名称"
                        name="name"
                        rules={[{ required: true, message: '请输入场地名称' }]}
                    >
                        <Input placeholder="请输入场地名称" />
                    </Form.Item>
                    <Form.Item
                        label="所属门店"
                        name="store_id"
                        rules={[{ required: true, message: '请选择所属门店' }]}
                    >
                        <Select placeholder="请选择所属门店">
                            {stores.map(store => (
                                <Option key={store.id} value={store.id}>{store.name}</Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item
                        label="场地类型"
                        name="venue_type"
                        rules={[{ required: true, message: '请选择场地类型' }]}
                    >
                        <Select 
                            placeholder="请选择场地类型"
                            dropdownRender={menu => (
                                <div>
                                    {menu}
                                    <Divider style={{ margin: '4px 0' }} />
                                    <div style={{ display: 'flex', flexWrap: 'nowrap', padding: 8 }}>
                                        <Input
                                            style={{ flex: 'auto' }}
                                            placeholder="输入新场地类型"
                                            id="new-venue-type"
                                        />
                                        <Button
                                            type="link"
                                            onClick={async () => {
                                                const typeName = document.getElementById('new-venue-type').value;
                                                if (typeName) {
                                                    try {
                                                        const res = await request('/api/v1/venue/type', {
                                                            method: 'POST',
                                                            data: {
                                                                name: typeName,
                                                                sort_order: 0,
                                                                status: 1
                                                            }
                                                        });
                                                        if (res.success) {
                                                            message.success('添加场地类型成功');
                                                            // 重新获取场地类型列表
                                                            fetchvenue_types();
                                                            // 设置当前选中的场地类型
                                                            venueForm.setFieldsValue({ venue_type: typeName });
                                                        } else {
                                                            message.error(res.message || '添加场地类型失败');
                                                        }
                                                    } catch (error) {
                                                        console.error('添加场地类型出错:', error);
                                                        message.error('添加场地类型失败');
                                                    }
                                                }
                                            }}
                                        >
                                            <PlusOutlined /> 添加
                                        </Button>
                                    </div>
                                </div>
                            )}
                        >
                            {venue_types.map(type => (
                                <Option key={type.value} value={type.value}>{type.label}</Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                label="容纳人数"
                                name="capacity"
                                rules={[{ required: true, message: '请输入容纳人数' }]}
                            >
                                <InputNumber placeholder="请输入容纳人数" style={{ width: '100%' }} min={1} />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                label="面积(平方米)"
                                name="area"
                                rules={[{ required: true, message: '请输入面积' }]}
                            >
                                <InputNumber placeholder="请输入面积" style={{ width: '100%' }} min={0} step={0.01} precision={2} />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                label="默认小时价格"
                                name="hour_price"
                                rules={[{ required: true, message: '请输入默认小时价格' }]}
                            >
                                <InputNumber placeholder="请输入默认小时价格" style={{ width: '100%' }} min={0} step={0.01} precision={2} />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                label="全天价格"
                                name="day_price"
                                rules={[{ required: true, message: '请输入全天价格' }]}
                            >
                                <InputNumber placeholder="请输入全天价格" style={{ width: '100%' }} min={0} step={0.01} precision={2} />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Form.Item
                        label="分时段定价"
                        name="time_based_pricing"
                    >
                        <TimeBasedPricingEditor />
                    </Form.Item>
                    <Form.Item
                        label="排序"
                        name="sort_order"
                    >
                        <InputNumber placeholder="请输入排序值" style={{ width: '100%' }} min={0} />
                    </Form.Item>
                    <Form.Item
                        label="状态"
                        name="status"
                        rules={[{ required: true, message: '请选择状态' }]}
                    >
                        <Select placeholder="请选择状态">
                            <Option value={1}>空闲中</Option>
                            <Option value={2}>使用中</Option>
                            <Option value={3}>保洁中</Option>
                            <Option value={4}>待保洁</Option>
                            <Option value={5}>维护中</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item
                        label="设施"
                        name="facilities"
                    >
                        <FacilityEditor />
                    </Form.Item>
                    <Form.Item
                        label="场地图片"
                        name="images"
                        tooltip="可上传多张场地图片，最多5张"
                    >
                        <ImageUploader multiple={true} />
                    </Form.Item>
                    <Form.Item
                        label="开放时间"
                        name="opening_hours"
                    >
                        <TextArea placeholder="请输入场地开放时间" rows={2} />
                    </Form.Item> 
                    <Form.Item
                        label="特殊提示"
                        name="special_notice"
                    >
                        <Input placeholder="请输入特殊提示" />
                    </Form.Item>
                    <Form.Item
                        label="场地描述"
                        name="description"
                    >
                        <TextArea placeholder="请输入场地描述" rows={4} />
                    </Form.Item>
                    <Form.Item>
                        <Space>
                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>
                            <Button onClick={() => setFormVisible(false)}>取消</Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Modal>
        </PageContainer>
    );
};

export default StoreVenue;